import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;

/**
 * 命令行执行
 */
public class CmdUtils {

    public static void main(String[] args) throws IOException, InterruptedException {
        System.out.println(getLocalIpByLinux());
    }

    public static String getLocalIpByLinux() throws IOException, InterruptedException {
        String cmd = "ifconfig eth0 |egrep 'inet ' |awk '{print $2}'";
        StringBuilder result = new StringBuilder();
        int res = callCmdForLinux(cmd, result);
        if (res == 0) {
            return result.toString().trim();
        }
        return null;
    }

    /**
     * 调用命令
     *
     * @param cmd
     * @param resultMsg
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    public static int callCmdForLinux(String cmd, StringBuilder resultMsg) throws IOException, InterruptedException {
        List<String> cmds = new LinkedList<>();
        cmds.add("sh");
        cmds.add("-c");
        cmds.add(cmd);
        ProcessBuilder pb = new ProcessBuilder(cmds);
        pb.redirectErrorStream(true);
        Process process = pb.start();
        readInput(process.getInputStream(), resultMsg);
//        readInput(process.getErrorStream(), null);
        process.waitFor();
        return process.exitValue();
    }

    public static void readInput(InputStream is, StringBuilder resultMsg) {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
            String line;
            while ((line = br.readLine()) != null) {
                if (resultMsg != null) {
                    if (resultMsg.length() == 0) {
                        resultMsg.append("\n");
                    }
                    resultMsg.append(line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
